﻿using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;
using System.Windows;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Windows.Threading;
using AutoStar.Common;
using System.Windows.Data;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.IO.Ports;
using System.Windows.Input;
using Microsoft.Win32;
using System.IO;
using Path = System.IO.Path;
using System.Reflection;
using System.IO.Pipes;
using System.Runtime.Serialization.Formatters.Binary;
using System.Threading;
using System.Timers;
using SharpGL;
using SharpGL.SceneGraph;
using SharpGL.WPF;
using Printer = AutoStar.Common.Printer;
using UploadInfo = AutoStar.Common.UploadInfo;
using Point3D = AutoStar.Common.Point3D;
using PrintChannel = AutoStar.Common.PrintChannel;
using Line3D = AutoStar.Common.Line3D;
using System.Windows.Media.Imaging;
using PrintProject = AutoStar.Common.PrintProject;
using System.Windows.Controls.Primitives;
using AutoStar.Views;
using AutoStar.Base;
using AutoStar.Models;
using AutoStar.Views.Pages;
using System.Security.Policy;
using System.Xml.Linq;
using System.Drawing;
using static AutoStar.Models.PrintSliceModel;
using static AutoStar.Models.MainWindowModel;
using Prism.Commands;
using System.Configuration;
using Newtonsoft.Json.Linq;

namespace AutoStar.ViewModel
{
    public class MainWindowVM : BaseViewModel
    {
        //public List<MenuModel> Menus { get; set; } = new List<MenuModel>();
        public ObservableCollection<MenuModel> Menus { get; set; } = new ObservableCollection<MenuModel>();


        public MainWindowVM()
        {
            InitializeMenus();
            InitializeCommands();
            StartTimer();
        }
        private void InitializeCommands()
        {
            MainWindow_Loaded = new RelayCommand(Load);
            LoginCommand = new RelayCommand(ExecuteLogin_Click);
            ExitCommand = new RelayCommand(ExecuteExit_Click);
            SaveFiles = new RelayCommand(SaveFiles_Click);
            CloseFiles = new RelayCommand(CloseFiles_Click);
            ExitProgram = new RelayCommand(ExecuteExitProgram_Click);
            OpenViewCommand = new DelegateCommand<object>(new Action<object>(p => OpenViewCommand_Click(p)));
            this.ExecuteOnUIThread = action => Application.Current.Dispatcher.Invoke(action);
        }
        private void InitializeMenus()
        {
            // 初始化一级菜单
            var menus = new List<MenuModel>
            {
                new MenuModel
                {
                    Header = "文件",
                    Icon = "\ue617",
                    SubMenus = new List<SubMenuModel>
                    {
                        new SubMenuModel { Header = "新建项目", TargetView = "新建项目" },
                        new SubMenuModel { Header = "打开项目", TargetView = "打开项目" },
                        new SubMenuModel { Header = "保存", TargetView = "保存" },
                        new SubMenuModel { Header = "关闭", TargetView = "关闭" },
                        new SubMenuModel { Header = "退出", TargetView = "退出" }
                    }
                },
                new MenuModel
                {
                    Header = "视图",
                    Icon = "\ue619",
                    SubMenus = new List<SubMenuModel>
                    {
                        new SubMenuModel { Header = "历史指令", TargetView = "历史指令" },
                        new SubMenuModel { Header = "表单视图", TargetView = "表单视图" }
                    }
                },
                new MenuModel
                {
                    Header = "项目",
                    Icon = "\ue612",
                    SubMenus = new List<SubMenuModel>
                    {
                        new SubMenuModel { Header = "打印层", TargetView = "打印层" },
                        new SubMenuModel { Header = "打印通道", TargetView = "打印通道" },
                        new SubMenuModel { Header = "打印数据", TargetView = "打印数据" }
                    }
                },
                new MenuModel
                {
                    Header = "调试",
                    Icon = "\ue616",
                    SubMenus = new List<SubMenuModel>
                    {
                        new SubMenuModel { Header = "三轴调试", TargetView = "三轴调试" },
                        new SubMenuModel { Header = "串口调试", TargetView = "串口调试" },
                        new SubMenuModel { Header = "打印参数", TargetView = "打印参数" },
                        new SubMenuModel { Header = "其他调试", TargetView = "其他调试" }
                    }
                },
                new MenuModel
                {
                    Header = "工具",
                    Icon = "\ue614",
                    SubMenus = new List<SubMenuModel>
                    {
                        new SubMenuModel { Header = "视频监控", TargetView = "视频监控" },
                        new SubMenuModel { Header = "导入GCode", TargetView = "导入GCode" },
                        new SubMenuModel { Header = "模型中心", TargetView = "模型中心" }
                    }
                },
                new MenuModel
                {
                    Header = "帮助",
                    Icon = "\ue613",
                    SubMenus = new List<SubMenuModel>
                    {
                        new SubMenuModel { Header = "硬件协议", TargetView = "硬件协议" },
                        new SubMenuModel { Header = "材料参数", TargetView = "材料参数" },
                        new SubMenuModel { Header = "设置", TargetView = "设置" }
                    }
                }
            };
            // 将菜单绑定到ViewModel
            Menus = new ObservableCollection<MenuModel>(menus);
        }

        private void OpenViewCommand_Click(object obj)
        {
            try
            {
                switch (obj)
                {
                    case "新建项目":
                        NewProject_Click();
                        break;
                    case "打开项目":
                        OpenFiles_Click();
                        break;
                    case "保存":
                        SaveFiles_Click();
                        break;
                    case "关闭":
                        CloseFiles_Click();
                        break;
                    case "退出":
                        ExecuteExitProgram_Click();
                        break;
                    case "历史指令":
                        ExecuteHistoryCommandShow_Click();
                        break;
                    case "表单视图":
                        ExecuteFormCommandShow_Click();
                        break;
                    case "打印状态":
                        SettingPageUrl = "./Pages/PrintStatusView.xaml";
                        break;
                    case "打印层":
                        Global.SliceVM.Add();
                        IsCurrentProjectEnable = true;
                        SettingPageUrl = "./Pages/PrintSliceView.xaml";
                        break;
                    case "打印通道":
                        break;
                    case "打印数据":
                        break;
                    case "三轴调试":
                        ExecuteWindowXYZ_Click();
                        break;
                    case "串口调试":
                        ExecuteSerial_Click();
                        break;
                    case "打印参数":
                        ExecutePrintParameterShow_Click();
                        break;
                    case "其他调试":
                        ExecuteWindowOther_Click();
                        break;
                    case "视频监控":
                        ExecuteVideoCommandShow_Click();
                        break;
                    case "导入GCode":
                        ExecuteImportGCodeCommandShow_Click();
                        break;
                    case "模型中心":
                        ExecuteModelCenterShow_Click();
                        break;
                    case "硬件协议":
                        ExecuteHelp1_Click();
                        break;
                    case "材料参数":
                        ExecuteHelp2_Click();
                        break;
                    case "设置":
                        ExecuteSettings_Click();
                        break;
                }
            }
            catch (Exception ex)
            {
                Global.LogHelper.WriteLog("switch case error：" + ex.Message);
            }
        }

        public DelegateCommand<object> OpenViewCommand { get; private set; }
        //public DelegateCommand<object> OpenViewCommand => new DelegateCommand<object>(new Action<object>(p =>
        //{
        //    var ddd = p;
        //}));
        public ICommand MainWindow_Loaded { get; private set; }
        public ICommand SaveFiles { get; private set; }
        public ICommand CloseFiles { get; private set; }
        public ICommand ExitProgram { get; private set; }


        public System.Timers.Timer timer = new System.Timers.Timer(interval: 2000);//用于检测是否是打印中空闲的定时器
        public bool _IsSelected = false;
        public bool IsSelected
        {
            get => _IsSelected;
            set => this.MutateVerbose(ref _IsSelected, value, RaisePropertyChanged());
        }


        public string _MenuItem;
        public string MenuItem
        {
            get => _MenuItem;
            set
            {
                if (_MenuItem != value)
                //if (string.IsNullOrEmpty( _MenuItem) && !string.IsNullOrEmpty(value))
                {
                    SetAndNotify(ref _MenuItem, value);
                }
            }
        }
        private string _settingPageUrl = "./Pages/MainView.xaml";
        public string SettingPageUrl { get => _settingPageUrl; set => this.MutateVerbose(ref _settingPageUrl, value, RaisePropertyChanged()); }
        public event EventHandler SettingChanged;
        public ICommand FuncSelectedCommand1 => new AnotherCommandImplementation(OnFuncSelected);

        private void OnFuncSelected(object parameter)
        {
            if (parameter is string menuItemName)
            {
                // 在这里处理菜单项的参数
                // 比如根据菜单项的名称执行相应的操作
            }
        }

        public ICommand FuncSelectedCommand => new AnotherCommandImplementation(p =>
        {
            var index = p.ToString();
            switch (index)
            {
                case "0":
                    SettingPageUrl = "./Pages/MainView.xaml";
                    break;
                case "1":
                    SettingPageUrl = "./Pages/PrintStatusView.xaml";
                    break;
                case "2":
                    SettingPageUrl = "./Pages/CurrentProjectView.xaml";
                    IsCurrentProjectEnable = true;
                    break;
                case "3":
                    SettingPageUrl = "./Pages/PrintSliceView.xaml";
                    break;
                case "4":
                    SettingPageUrl = "./Pages/PrintChannelView.xaml";
                    break;
            }
        });
        private void MenuEnabled(int type)
        {
            if (type == 2)
            {
                IsCurrentProjectEnable = true;
                //IsPrintLayerEnable = true;
                //IsPrintChannelEnable = true;
            }
            else if (type == 1)
            {
                IsCurrentProjectEnable = false;
                //IsPrintLayerEnable = false;
                //IsPrintChannelEnable = false;
            }
        }
        public ICommand LoginCommand { get; set; }
        public ICommand ExitCommand { get; set; }
        public Action<Action> ExecuteOnUIThread { get; set; }
        #region 命令---窗体Showdialog

        private void ExecuteWindowXYZ_Click()
        {
            try
            {
                Global.WindowXYZ.Show();
                if (Global.WindowXYZVM.SelectedLocation.Equals("绝对位置"))
                {
                    Global.WindowXYZVM.XValue = (Global.UploadInfo.xLocation / 1000).ToString();
                    Global.WindowXYZVM.YValue = (Global.UploadInfo.yLocation / 1000).ToString();
                    Global.WindowXYZVM.ZValue = (Global.UploadInfo.zLocation / 1000).ToString();
                }
            }
            catch (Exception ex)
            {
                Global.LogHelper.WriteLog("Settings XYZ Error:" + ex.Message);
            }
        }

        private void ExecuteWindowSlice_Click()
        {
            var windowSlice = Global.WindowSlice;
            windowSlice.WindowStartupLocation = WindowStartupLocation.CenterOwner;
            //windowSlice.Owner = Application.Current.MainWindow;
            windowSlice.ShowDialog();
        }
        /// <summary>
        /// 左侧菜单栏-调试--其他调试
        /// </summary>
        private void ExecuteWindowOther_Click()
        {
            try
            {
                var windowOther = new WindowOther();
                windowOther.WindowStartupLocation = WindowStartupLocation.CenterOwner;
                windowOther.Show();
            }
            catch (Exception ex)
            {
                Global.LogHelper.WriteLog("Other Commands Error:" + ex.Message);
            }
        }
        /// <summary>
        /// 左侧菜单栏-工具--视频
        /// </summary>
        private void ExecuteVideoCommandShow_Click()
        {
            var videoWindow = new WindowMonitor();
            videoWindow.WindowStartupLocation = WindowStartupLocation.CenterOwner;
            //videoWindow.Owner = Application.Current.MainWindow;
            videoWindow.Show();
        }
        /// <summary>
        /// 左侧菜单栏-视图--历史指令
        /// </summary>
        private void ExecuteHistoryCommandShow_Click()
        {
            try
            {

                var historyWindow = new WindowCommandHistory();
                historyWindow.WindowStartupLocation = WindowStartupLocation.CenterOwner;
                //historyWindow.Owner = Application.Current.MainWindow;
                historyWindow.ShowDialog();
            }
            catch (Exception ex)
            {
                Global.LogHelper.WriteLog("History Commands Error:" + ex.Message);
            }

        }
        /// <summary>
        /// 导入GCode
        /// </summary>
        private void ExecuteImportGCodeCommandShow_Click()
        {
            try
            {

                var importGCodeWindow = new WindowImportGCode();
                importGCodeWindow.WindowStartupLocation = WindowStartupLocation.CenterOwner;
                //importGCodeWindow.Owner = Application.Current.MainWindow;
                importGCodeWindow.ShowDialog();
            }
            catch (Exception ex)
            {
                Global.LogHelper.WriteLog("GCode Command Error:" + ex.Message);
            }
        }
        /// <summary>
        /// 左侧菜单栏-项目--打印层
        /// </summary>
        private void ExecutePrintLayerShow_Click()
        {
            var printLayerWindow = new WindowLayer();
            printLayerWindow.WindowStartupLocation = WindowStartupLocation.CenterOwner;
            printLayerWindow.Show();
        }
        #endregion

        /// <summary>
        /// 左侧菜单栏-文件--新建
        /// </summary>
        private void NewProject_Click()
        {
            Global.printProject = new PrintProject();
            flushProjectLabel();
            //Global.PrintChannelVM.SelectedChannel = 0;
            IsCurrentProjectEnable = true;
            Global.CurrentProjectVM.ModelList.Clear();
            SettingPageUrl = "./Pages/CurrentProjectView.xaml";
        }
        /// <summary>
        /// 左侧菜单栏-文件--打开
        /// </summary>
        private void OpenFiles_Click()
        {
            try
            {
                string path = Path.GetDirectoryName(AppDomain.CurrentDomain.BaseDirectory)
                                 + Path.DirectorySeparatorChar.ToString() + "PrintProject";
                OpenFileDialog openFile = new OpenFileDialog
                {
                    Title = "打开项目",
                    InitialDirectory = path,
                    //Filter = "GCode文件|*.gcode|All files (*.*)|*.*"
                    //Filter = "GCode文件|*.gcode|Wavefront OBJ文件|*.obj"
                    //Filter = "GCode文件|*.gcode|Wavefront OBJ文件|*.obj|STL文件|*.stl|所有文件|*.*"
                    Filter = "所有支持的文件|*.gcode;*.obj;*.stl|GCode文件|*.gcode|Wavefront OBJ文件|*.obj|STL文件|*.stl"
                    //Filter = "All files (*.*)|*.*"
                };
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                if (openFile.ShowDialog() == true)
                {
                    if (openFile.FileName.Contains(".gcode"))
                        Global.printProject.printLayers = AnalysisGCode.ParseGCode(openFile.FileName);
                    else if (openFile.FileName.Contains(".obj"))
                        Global.printProject = Utilities.ReadObject<PrintProject>(openFile.FileName);
                    //Global.printProject = Utilities.ReadObject<PrintProject>(openFile.FileName);
                    //Utilities.ReadGCodeFile(openFile.FileName);

                    flushProjectLabel();
                    Global.SliceVM.flushDgv();
                    //Global.MainVM.flushDgv();
                    Global.PrintChannelVM.SelectedChannel = 0;
                    IsCurrentProjectEnable = true;
                }
            }
            catch (Exception ex)
            {
                Global.LogHelper.WriteLog("Open Files Error:" + ex.Message);
            }
        }

        /// <summary>
        /// 左侧菜单栏-文件--保存
        /// </summary>
        private void SaveFiles_Click()
        {
            try
            {
                if (Global.printProject == null)
                {
                    MessageBox.Show("当前未打开项目");
                    return;
                }
                string path = Path.GetDirectoryName(AppDomain.CurrentDomain.BaseDirectory)
                             + Path.DirectorySeparatorChar.ToString() + "PrintProject";
                SaveFileDialog save = new SaveFileDialog
                {
                    Title = "保存项目",
                    InitialDirectory = path,
                    FileName = Global.printProject.name + Global.printProject.id + ".obj",
                    Filter = "Wavefront OBJ文件|*.obj"
                };
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                //save.ShowDialog();
                if (save.ShowDialog() == true && save.FileName != string.Empty)
                {
                    Utilities.SaveObject(save.FileName, Global.printProject);
                    //statusTips.Text = "项目已保存";
                }
            }
            catch (Exception ex)
            {
                Global.LogHelper.WriteLog("Save Files Error:" + ex.Message);
            }
        }
        /// <summary>
        /// 左侧菜单栏-文件--关闭
        /// </summary>
        private void CloseFiles_Click()
        {
            try
            {
                Global.printProject = new PrintProject();
                Global.SliceVM.DataGridLists = new System.Collections.ObjectModel.ObservableCollection<PrintSliceItem>();
                Global.SliceVM.ImageSource = null;
                MenuEnabled(1);
                SettingPageUrl = "./Pages/MainView.xaml";
            }
            catch (Exception ex)
            {
                Global.LogHelper.WriteLog("Close Files Error:" + ex.Message);
            }
        }
        /// <summary>
        /// 左侧菜单栏-文件--退出
        /// </summary>
        private void ExecuteExitProgram_Click()
        {
            try
            {
                Global.LogHelper.WriteLog("3DPrinterSoftware Exit");
                StopTimer();
                System.Environment.Exit(0);
            }
            catch (Exception ex)
            {
                Global.LogHelper.WriteLog("Exit Error:" + ex.Message);
            }
        }

        private void ExecuteLogin_Click()
        {
            WindowLogin loginWindow = new WindowLogin();
            loginWindow.WindowStartupLocation = WindowStartupLocation.CenterScreen;
            loginWindow.ShowDialog();
        }
        /// <summary>
        /// 串口调试
        /// </summary>
        private void ExecuteSerial_Click()
        {
            try
            {
                if (Global.WindowSerial != Application.Current.MainWindow)
                {
                    // 设置 Global.WindowSerial 的 Owner 为主窗口
                    Global.WindowSerial.Owner = Application.Current.MainWindow;
                    // 设置窗口启动位置为居中于 Owner 窗口
                    Global.WindowSerial.WindowStartupLocation = WindowStartupLocation.CenterOwner;
                }
                else
                {
                    // 如果 Global.WindowSerial 是主窗口，则设置为居中屏幕
                    Global.WindowSerial.WindowStartupLocation = WindowStartupLocation.CenterScreen;
                }
                // 显示窗口
                Global.WindowSerial.Show();
            }
            catch (Exception ex)
            {
                Global.LogHelper.WriteLog("Serial Commands Error:" + ex.Message);
            }
        }

        private void ExecuteSettings_Click()
        {
            SettingPageUrl = "./Pages/SettingView.xaml";
        }
        /// <summary>
        /// 左侧菜单栏-帮助--打印材料参数
        /// </summary>
        private void ExecuteHelp2_Click()
        {
            try
            {
                string path = Path.GetDirectoryName(AppDomain.CurrentDomain.BaseDirectory)
                             + Path.DirectorySeparatorChar.ToString() + "Help";
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                System.Diagnostics.Process.Start(path);
            }
            catch (Exception ex)
            {
                Global.LogHelper.WriteLog("Help2 Error:" + ex.Message);
            }
        }
        /// <summary>
        /// 左侧菜单栏-帮助--硬件指令协议
        /// </summary>
        private void ExecuteHelp1_Click()
        {
            try
            {
                string path = Path.GetDirectoryName(AppDomain.CurrentDomain.BaseDirectory)
                             + Path.DirectorySeparatorChar.ToString() + "Help";
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                System.Diagnostics.Process.Start(path);
            }
            catch (Exception ex)
            {
                Global.LogHelper.WriteLog("Help1 Error:" + ex.Message);
            }
        }
        /// <summary>
        /// 左侧菜单栏-工具--模型中心
        /// </summary>
        /// <exception cref="NotImplementedException"></exception>
        private void ExecuteModelCenterShow_Click()
        {
        }

        /// <summary>
        /// 左侧菜单栏-调试--打印参数
        /// </summary>
        /// <exception cref="NotImplementedException"></exception>
        private void ExecutePrintParameterShow_Click()
        {
            try
            {

            }
            catch (Exception ex)
            {
                Global.LogHelper.WriteLog("Print Parameters Error:" + ex.Message);
            }
        }

        /// <summary>
        /// 左侧菜单栏-项目--打印数据
        /// </summary>
        /// <exception cref="NotImplementedException"></exception>
        private void ExecutePrintDataShow_Click()
        {
        }

        /// <summary>
        /// 左侧菜单栏-项目--打印通道
        /// </summary>
        /// <exception cref="NotImplementedException"></exception>
        private void ExecutePrintChannelShow_Click()
        {
        }

        /// <summary>
        /// 左侧菜单栏-视图--打印状态
        /// </summary>
        /// <exception cref="NotImplementedException"></exception>
        private void ExecutePrintStatusCommandShow_Click()
        {

        }

        /// <summary>
        /// 左侧菜单栏-视图--表单视图
        /// </summary>
        /// <exception cref="NotImplementedException"></exception>
        private void ExecuteFormCommandShow_Click()
        {
            try
            {

            }
            catch (Exception ex)
            {
                Global.LogHelper.WriteLog("Form Show Error:" + ex.Message);
            }
        }

        public void SetOpenGLControl1Width(double width, double height)
        {
            //openGLControl1Width = width;
            //openGLControl1Height = height;
        }
        public void SetOpenGLControl2Width(double width, double height)
        {
            openGLControl2Width = width;
            openGLControl2Height = height;
        }
        public float planeHeight = 60;
        public event EventHandler OpenGLDraw;

        private void CloseWindow()
        {
            OnRequestClose();
        }
        private string _PrintStatuslbl = "停止";
        public string PrintStatuslbl
        {
            get => _PrintStatuslbl;
            set => Set(ref _PrintStatuslbl, value);
        }
        public event Action<string, string> ShowMessageBoxRequested;
        public void SwitchSerial()
        {
            if (isOpen)
            {
                try
                {
                    Global.printer.serialPortController.serialPort.Close();
                    Global.printStatusVM.PortStatuslbl = "关闭";
                    Global.serialVM.ReceiveListBox.Clear();
                    Global.serialVM.SendListBox.Clear();

                }
                catch (Exception ex)
                {
                    ShowMessageBoxRequested?.Invoke("错误", ex.Message);
                }
                //原菜单栏图标修改
                //toolStripButton1.Image = Properties.Resources.开关3;
                //statusTips.Text = "串口已关闭";
            }
            else
            {
                if (Global.printer.serialPortController.names.Length == 0)
                    return;
                try
                {
                    Global.printer.serialPortController.serialPort.Open();
                    Global.printStatusVM.PortStatuslbl = "打开";
                    Application.Current.Dispatcher.Invoke(() =>
                    {
                        Global.printStatusVM.PortStatuslbl = "打开";
                    });
                }
                catch (Exception ex)
                {
                    ShowMessageBoxRequested?.Invoke("错误", ex.Message);
                    return;
                }
                //原菜单栏图标修改
                //toolStripButton1.Image = Properties.Resources.开关4;
                //statusTips.Text = "串口已打开";
            }
            isOpen = !isOpen;
        }
        #region 定义属性
        private string _LogoPath = "/Assets/images/微纳图标.png";
        public string LogoPath
        {
            get
            {
                if (ConfigurationManager.AppSettings["LogoPath"] != null)
                    return ConfigurationManager.AppSettings["LogoPath"];
                else
                    return _LogoPath;
            }
            set => Set(ref _LogoPath, value);
        }
        private bool _IsPrinterEnable = true;
        public bool IsPrinterEnable
        {
            get => _IsPrinterEnable;
            set => Set(ref _IsPrinterEnable, value);
        }
        private bool _IsNewProjectEnable = true;
        public bool IsNewProjectEnable
        {
            get => _IsNewProjectEnable;
            set => Set(ref _IsNewProjectEnable, value);
        }
        private bool _IsCurrentProjectEnable = false;
        public bool IsCurrentProjectEnable
        {
            get => _IsCurrentProjectEnable;
            set => Set(ref _IsCurrentProjectEnable, value);
        }
        private bool _IsPrintLayerEnable = true;
        public bool IsPrintLayerEnable
        {
            get => _IsPrintLayerEnable;
            set => Set(ref _IsPrintLayerEnable, value);
        }
        private bool _IsPrintChannelEnable = true;
        public bool IsPrintChannelEnable
        {
            get => _IsPrintChannelEnable;
            set => Set(ref _IsPrintChannelEnable, value);
        }
        private OpenGLControl _openGLControl;
        public OpenGLControl openGLControl1
        {
            get => _openGLControl;
            set => Set(ref _openGLControl, value);
        }
        private static OpenGLControl _openGLContro2;
        public OpenGLControl openGLControl2
        {
            get => _openGLContro2;
            set => Set(ref _openGLContro2, value);
        }
        private DispatcherTimer timeTimer;
        private string _timeText;
        public string TimeText
        {
            get => _timeText;
            set => Set(ref _timeText, value);
        }


        private bool _isAutoRotate = false;
        public bool IsAutoRotate
        {
            get => _isAutoRotate;
            set => Set(ref _isAutoRotate, value);
        }
        //private double _numericValue = 0.00;

        //public double NumericValue
        //{
        //    get => _numericValue;
        //    set => Set(ref _numericValue, Math.Round(value / step) * step);
        //}
        private double _numericValue2 = 60;

        public double NumericValue2
        {
            get => _numericValue2;
            set => Set(ref _numericValue2, Math.Round(value / step) * step);
        }
        //private double _openGLControl1Width;
        //public double openGLControl1Width
        //{
        //    get => _openGLControl1Width;
        //    set => Set(ref _openGLControl1Width, value);
        //}
        //private double _openGLControl1Height;
        //public double openGLControl1Height
        //{
        //    get => _openGLControl1Height;
        //    set => Set(ref _openGLControl1Height, value);
        //}
        private double _openGLControl2Width;
        public double openGLControl2Width
        {
            get => _openGLControl2Width;
            set => Set(ref _openGLControl2Width, value);
        }
        private double _openGLControl2Height;
        public double openGLControl2Height
        {
            get => _openGLControl2Height;
            set => Set(ref _openGLControl2Height, value);
        }

        private bool _isRotating;
        public bool IsRotating
        {
            get => _isRotating;
            set => Set(ref _isRotating, value);
        }
        private double _MainWidth;
        public double MainWidth
        {
            get => _MainWidth;
            set => Set(ref _MainWidth, value);
        }
        private string _VersionText;
        public string VersionText
        {
            get => _VersionText;
            set => Set(ref _VersionText, value);
        }
        private double _MainHeight;
        public double MainHeight
        {
            get => _MainHeight;
            set => Set(ref _MainHeight, value);
        }

        double step = 0.25;
        private bool isOpen = false;
        #endregion
        //public static Printer printer = Printer.GetPrinter(150, 130, 100);//打印机
        //public static PrintProject printProject;//打印项目
        //打印机属性
        //private Printer _printer = Printer.GetPrinter(150, 130, 100);
        //public Printer printer
        //{
        //    get => _printer;
        //    set => Set(ref _printer, value);
        //}
        ////打印项目
        //private PrintProject _printProject = new PrintProject();
        //public PrintProject printProject 
        //{ 
        //    get => _printProject; 
        //    set => Set(ref _printProject, value); 
        //}
        //static Printer printer = Global.printer;//打印机
        //PrintProject printProject = Global.printProject;//打印项目
        #region 业务Load加载事件

        public void Load()
        {
            Global.printer.serialPortController.names = SerialPort.GetPortNames();
            if (Global.printer.serialPortController.names.Length > 0)
            {
                Global.printer.serialPortController.serialPort.PortName = Global.printer.serialPortController.names[Global.printer.serialPortController.names.Length - 1];
            }
            Global.printer.serialPortController.serialPort.BaudRate = 115200;
            Global.printer.serialPortController.serialPort.DataBits = 8;
            Global.printer.serialPortController.serialPort.StopBits = StopBits.One;
            Global.printer.serialPortController.serialPort.Parity = Parity.None;

            //HidePages();

            //初始化事件
            Global.printer.serialPortController.sendDataEvent += Serial_sendDataEvent;
            Global.printer.serialPortController.receiveDataEvent += Serial_receiveDataEvent;
            timer.Elapsed += Timer_Elapsed;
            timerIsStop.Elapsed += TimerIsStop_Elapsed;
            timerIsStop.AutoReset = true;//必须加，否则停不下来
            closeSolidfyLight.Elapsed += CloseSolidfyLight_Elapsed;
            _openGLControl = new OpenGLControl();
            _openGLContro2 = new OpenGLControl();
        }

        public System.Timers.Timer timerIsStop = new System.Timers.Timer(interval: 100);
        public System.Timers.Timer closeSolidfyLight = new System.Timers.Timer(100);
        private void Serial_sendDataEvent(string value)
        {
            Global.printer.commandHistory.Add(value);
            Global.serialVM.SendDataEvent(value);
        }
        /// <summary>
        /// 串口接收数据
        /// </summary>
        /// <param name="value"></param>
        private void Serial_receiveDataEvent(string value)
        {
            Global.serialVM.GetDataEvent(value);
            UploadInfo info = Utilities.hexStrToInfo(value);
            Global.UploadInfo = info;
            Global.printer.X = info.xLocation / 1000;
            Global.printer.Y = info.yLocation / 1000;
            Global.printer.Z = info.zLocation / 1000;
            Global.printStatusVM.lblX = (info.xLocation / 1000).ToString("");
            Global.printStatusVM.lblY = (info.yLocation / 1000).ToString("");
            Global.printStatusVM.lblZ = (info.zLocation / 1000).ToString("");
            Global.printStatusVM.PortStatuslbl = "打开";
            Global.printStatusVM.PrintStatuslbl = "正常";
            //因为要访问ui资源，所以需要使用invoke方式同步ui。  
            //this.ExecuteOnUIThread((EventHandler)delegate
            Action action = () =>
            {
                switch (info.sysStatus)
                {
                    case "80":
                        if (Global.printer.printerState == 0)
                        {
                            break;
                        }
                        timer.Start();
                        break;
                    case "82":
                        tagTimer = 0;
                        if (Global.printer.printerState == 1)
                        {
                            break;
                        }
                        Global.printer.printerState = 1;
                        PrintStatuslbl = "打印中";
                        break;
                    case "83":
                        timer.Stop();
                        if (Global.printer.printerState == 2)
                        {
                            break;
                        }
                        Global.printer.printerState = 2;
                        PrintStatuslbl = "打印中暂停";
                        break;
                }
                //显示状态
                Global.printStatusVM.lblX = string.Format("{0:F2}", Global.printer.X);
                Global.printStatusVM.lblY = string.Format("{0:F2}", Global.printer.Y);
                Global.printStatusVM.lblZ = string.Format("{0:F2}", Global.printer.Z);
                Global.printStatusVM.lblChannel = info.CurChannelNum + "";
                Global.printStatusVM.lblBattery = Utilities.currentToPressure(info.AirPress) + "（KPa）";
                Global.printStatusVM.lblAirPress = info.Temperature + "（℃）";
                Global.printStatusVM.lblPrintSpace = info.PrintDistance + "（um）";
                Global.printStatusVM.lblStartTime = info.OpenTime + "（us）";
                Global.printStatusVM.lblWorkMode = "点喷式";
            };
            this.ExecuteOnUIThread(action);
        }

        private void TimerIsStop_Elapsed(object sender, ElapsedEventArgs e)
        {
            if (Global.printer.printerState == 0)
            {
                timerIsStop.Stop();
                Global.printer.printerState = 1;
                //Global.printer.SendGCode("M250");//打开固化灯
                //暂时无用 要给固化灯一个开关等待时间 最小为1秒 发送指令中延迟1秒 不现实 
                //先改为结束后关闭固化灯
                //Thread.Sleep(Global.printProject.printLayers[Global.printer.layerIndex].solidfyTime * 1000);
                //Global.printer.SendGCode("M251");//关闭固化灯
                Global.printer.printerState = 0;
                if (Global.printer.layerIndex < Global.printProject.printLayers.Count - 1)
                {
                    Global.SliceVM.CountNum++;
                    Global.SliceVM.Progress = 0;
                    Global.printer.layerIndex++;
                    Thread thread = new Thread(new ThreadStart(Global.SliceVM.LoadLayerData))
                    {
                        IsBackground = true
                    };
                    thread.Start();
                }
                else
                {
                    if (Global.SliceVM.originalLayers != null && Global.SliceVM.originalLayers.Count() > Global.printProject.printLayers.Count())
                        Global.printProject.printLayers = new List<PrintLayer>(Global.SliceVM.originalLayers);
                    if (Global.printParaVM.PrintParaLayers != null && Global.printParaVM.PrintParaLayers.Count() > Global.printProject.printLayers.Count())
                        Global.printProject.printLayers = new List<PrintLayer>(Global.printParaVM.PrintParaLayers);
                    MessageBox.Show("全部打印完成");
                    Global.SliceVM.CountNum = 1;
                    Global.SliceVM.TotalCount = "";
                    Global.SliceVM.Progress = 0;
                    //Global.printer.SendGCode("M251");//关闭固化灯
                    Global.SliceVM.flushDgv();
                }
                return;
            }
        }
        /// <summary>
        /// 打印层 切片后的datagridview  
        /// </summary>
        public void flushDgv()//刷新打印层的dgv
        {
            if (lines != null)
            {
                lines.Clear();
            }
            Global.SliceVM.DataGridLists.Clear();
            for (int i = 0; i < Global.printProject.printLayers.Count; i++)
            {
                PrintSliceItem item = new PrintSliceItem();
                item.层序号 = i + 1;
                switch (Global.printProject.printLayers[i].mode)
                {
                    case 0:
                        item.打印类型 = "蛇形";
                        break;
                    case 1:
                        item.打印类型 = "回形";
                        break;
                    case 2:
                        item.打印类型 = "网格形";
                        break;
                    case 10:
                        item.打印类型 = "纵向填充";
                        break;
                    case 11:
                        item.打印类型 = "横向填充";
                        break;
                    case 12:
                        item.打印类型 = "纵横交替";
                        break;
                    case 15:
                        item.打印类型 = "无填充";
                        break;
                }
                item.打印通道 = Global.printProject.printLayers[i].channel + 1;
                item.固化灯 = Global.printProject.printLayers[i].CuringLamp ? "开" : "关";
                Global.SliceVM.DataGridLists.Add(item);
                for (int j = 1; j < Global.printProject.printLayers[i].points.Count - 1; j++)
                {
                    Line3D line3D = new Line3D
                    {
                        start = Global.printProject.printLayers[i].points[j],
                        end = Global.printProject.printLayers[i].points[j + 1]
                    };
                    if (line3D.end.mode == 1)
                    {
                        lines.Add(line3D);
                    }
                }
            }
        }
        /// <summary>
        /// 编辑所有层 打印层 切片后的datagridview  
        /// </summary>
        public void flushDgvNew(PrintLayer layerChanged)//刷新打印层的dgv
        {
            if (lines != null)
            {
                lines.Clear();
            }
            Global.SliceVM.DataGridLists.Clear();
            for (int i = 0; i < Global.printProject.printLayers.Count; i++)
            {
                PrintSliceItem item = new PrintSliceItem();
                item.层序号 = i + 1;
                switch (Global.printProject.printLayers[i].mode)
                {
                    case 0:
                        item.打印类型 = "蛇形";
                        break;
                    case 1:
                        item.打印类型 = "回形";
                        break;
                    case 2:
                        item.打印类型 = "网格形";
                        break;
                    case 10:
                        item.打印类型 = "纵向填充";
                        break;
                    case 11:
                        item.打印类型 = "横向填充";
                        break;
                    case 12:
                        item.打印类型 = "纵横交替";
                        break;
                }
                item.打印通道 = Global.printProject.printLayers[i].channel + 1;
                item.固化灯 = Global.printProject.printLayers[i].CuringLamp ? "开" : "关";
                Global.SliceVM.DataGridLists.Add(item);
                for (int j = 1; j < Global.printProject.printLayers[i].points.Count - 1; j++)
                {
                    // 编辑所有层  目前只支持 编辑XY
                    Global.printProject.printLayers[i].x_start = (float)Convert.ToDouble(Global.layerVM.X);
                    Global.printProject.printLayers[i].y_start = (float)Convert.ToDouble(Global.layerVM.Y);
                    Line3D line3D = new Line3D
                    {
                        start = Global.printProject.printLayers[i].points[j],
                        end = Global.printProject.printLayers[i].points[j + 1]
                    };
                    if (line3D.end.mode == 1)
                    {
                        lines.Add(line3D);
                    }
                }
            }
        }
        /// <summary>
        /// 刷新当前项目参数
        /// </summary>
        public void flushProjectLabel()
        {
            var printProject = Global.printProject;
            if (printProject != null)
            {
                Global.CurrentProjectVM.ProjectName = printProject.name;
                Global.CurrentProjectVM.ProjectNum = printProject.id;
                Global.CurrentProjectVM.CreateTime = printProject.createTime.ToString();
                Global.CurrentProjectVM.UpdateTime = printProject.updateTime.ToString();
                Global.CurrentProjectVM.ModelMult = printProject.model.multiple.ToString();
                Global.CurrentProjectVM.XMove = printProject.model.moveX.ToString();
                Global.CurrentProjectVM.YMove = printProject.model.moveY.ToString();
                Global.CurrentProjectVM.ZMove = printProject.model.moveZ.ToString();
                flashChannellabel();
            }
        }

        /// <summary>
        /// 打印通道5个工作模式文本刷新  
        /// 缺少 btnModifyChannel_Click
        /// </summary>
        private void flashChannellabel()
        {
            try
            {
                Global.PrintChannelVM.Group1ViewModels = new ObservableCollection<PrinChannelModel>[6];
                for (int i = 0; i < 6; i++)
                {
                    var channel = Global.printProject.printChannels[i];
                    Global.PrintChannelVM.Group1ViewModels[i] = new ObservableCollection<PrinChannelModel>();
                    var model = new PrinChannelModel
                    {
                        text21 = channel.AirPress,
                        text22 = channel.Temperature,
                        text23 = channel.PrintSpeed / 60,
                        text24 = channel.T1,
                        text25 = channel.T2,
                        text26 = channel.T3,
                        text27 = channel.position.X,
                        text28 = channel.position.Y,
                    };
                    Global.PrintChannelVM.Group1ViewModels[i].Add(model);
                }
                //默认通道1
                Global.PrintChannelVM.Group1ViewModel = Global.PrintChannelVM.Group1ViewModels[0];
                //    Global.PrintChannelVM.ChannelList = new ObservableCollection<string>()
                //{
                //    "通道1","通道2","通道3","通道4","通道5","通道6","调试通道"
                //};
            }
            catch (Exception ex)
            {
                Global.LogHelper.WriteLog("flashChannellabel error：" + ex.Message);
            }
        }



        //private void LoadLayerData()
        //{
        //    List<Point3D> points = Global.printProject.printLayers[Global.printer.layerIndex].points;
        //    Global.printer.channelIndex = Global.printProject.printLayers[Global.printer.layerIndex].channel;
        //    if (points.Count > 0)
        //    {
        //        Global.printer.toPoint(points[0]);//该行是为了正确移动到打印顶点
        //    }
        //    setChannel(Global.printProject.printLayers[Global.printer.layerIndex].channel);//打印一层之前先设定当前层的通道
        //    ////进度条,暂时不增加
        //    //Invoke(new EventHandler(delegate
        //    //{
        //    //    toolStripProgressBar1.Maximum = points.Count;
        //    //}));
        //    //for (int j = 1; j < points.Count; j++)
        //    //{
        //    //    Invoke(new EventHandler(delegate
        //    //    {
        //    //        toolStripProgressBar1.Value = j + 1;
        //    //    }));
        //    //    printer.toPoint(points[j]);
        //    //}
        //    //new PrintChannel().setAirPress(0);//打印完一层后将气压设置为0
        //    if (Global.printProject.printLayers[Global.printer.layerIndex].solidfyTime != 0)
        //    {
        //        Global.printer.moveToSolidifyZero();
        //    }
        //    timerIsStop.Start();
        //}
        /// <summary>
        /// 重新设置通道  发送指令 
        /// </summary>
        /// <param name="index"></param>
        public void setChannel(int index)
        {
            Global.printer.channelIndex = index;
            switch (index)
            {
                case int n when n < 7:
                    PrintChannel.setChannel(Global.printProject.printChannels[index].ChannelID);
                    if (Global.printProject.printChannels[index].ChannelType.Contains("升温"))
                        Global.printProject.printChannels[index].setTemperature
                            (Global.printProject.printChannels[index].ChannelID, Global.printProject.printChannels[index].Temperature);
                    if (Global.printProject.printChannels[index].ChannelType.Contains("降温"))
                        Global.printProject.printChannels[index].setLowTemperture
                            (Global.printProject.printChannels[index].ChannelID, Global.printProject.printChannels[index].Temperature);
                    //if (index == 6 && Global.SliceVM.IsChangeAirPress==1)
                    //{
                    //    PrintChannel.setChannel(1);
                    //    Global.printProject.printChannels[0].setAirPress();
                    //    PrintChannel.setChannel(Global.printProject.printChannels[index].ChannelID);
                    //}
                    break;
                default:
                    break;
            }
            //if (index < 7)
            //{
            //    PrintChannel.setChannel(index);
            //    if (index == 6)
            //        Global.printProject.printChannels[index].setTemperature();
            //}
            Global.printProject.printChannels[index].setAirPress();
            Global.printProject.printChannels[index].setPrintSpeed();
            Global.printProject.printChannels[index].setT1T2T3();

            Global.printStatusVM.lblChannel = "通道"+ Global.printProject.printChannels[index].ChannelID;
            Global.printStatusVM.lblBattery = Global.printProject.printChannels[index].AirPress+"";
            Global.printStatusVM.lblAirPress = Global.printProject.printChannels[index].Temperature+"";
            //Global.printer.channelIndex = index;
            //if (Global.printer.channelIndex < 7)
            //{
            //    //PrintChannel.setChannel(Global.printProject.printChannels[index].ChannelID);
            //    PrintChannel.setChannel(Global.printer.channelIndex);
            //    Global.printProject.printChannels[Global.printer.channelIndex].setTemperature();
            //}
            //Global.printProject.printChannels[Global.printer.channelIndex].setAirPress();
            //Global.printProject.printChannels[Global.printer.channelIndex].setPrintSpeed();
            //Global.printProject.printChannels[Global.printer.channelIndex].setT1T2T3();
        }
        private void CloseSolidfyLight_Elapsed(object sender, ElapsedEventArgs e)
        {
            if (Global.printer.printerState == 0)
            {
                closeSolidfyLight.Stop();
                Global.printer.printerState = 1;
                Thread.Sleep(Global.printProject.printLayers[Global.printer.layerIndex].solidfyTime * 1000);
                Global.printer.printerState = 0;
                Global.printer.SendGCode("M251");//关闭固化灯
            }
        }
        int look = 300;
        int look2 = 150;
        private void OpenGLControl1_MouseWheel(object sender, MouseWheelEventArgs e)
        {
            if (e.Delta != 0)
            {
                if (look - e.Delta / 10 < 0)
                {
                    return;
                }
                look -= e.Delta / 10;
            }
        }

        private void OpenGLControl2_MouseWheel(object sender, MouseWheelEventArgs e)
        {
            if (e.Delta != 0)
            {
                if (e.Delta < 0)
                {
                    look2 -= e.Delta / 50;
                }
                else
                {
                    look2 -= e.Delta / 50;
                }
            }
        }
        //List<Line3D> lines = new List<Line3D>();//用于在状态监测界面画路径的线

        List<Line3D> lines = Global.lines;
        #endregion
        #region timer
        public int tagTimer = 0;
        private void Timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            tagTimer++;
            if (tagTimer > 1)
            {
                Global.printer.printerState = 0;
                timer.Stop();
                tagTimer = 0;
            }
        }
        #endregion
        private void ExecuteExit_Click()
        {
            Global.LogHelper.WriteLog("3DPrinterSoftware Exit");
            System.Environment.Exit(0);
        }
        private void StartTimer()
        {
            timeTimer = new DispatcherTimer();
            timeTimer.Tick += Timer_Tick;
            timeTimer.Interval = new TimeSpan(0, 0, 1); // 设置时间间隔为1秒  
            timeTimer.Start();
        }
        private void Timer_Tick(object sender, EventArgs e)
        {
            // 获取当前时间并格式化  
            string currentTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            char iconChar = (char)0xE619;
            string icon = iconChar.ToString();
            TimeText = icon + "   " + currentTime + "   ";
        }
        private void StopTimer()
        {
            if (timeTimer != null)
            {
                timeTimer.Tick -= Timer_Tick; // 取消绑定 Tick 事件处理程序
                timeTimer.Stop(); // 停止计时器
                timeTimer = null; // 释放计时器实例
            }
        }
        /// <summary>
        /// 打印通道    修改按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnModifyChannel_Click(object sender, EventArgs e)
        {
            //if (btnModifyChannel.Text == "修改")
            //{
            //    txtAirPress.ReadOnly = false;
            //    txtTemperature.ReadOnly = false;
            //    txtPrintSpeed.ReadOnly = false;
            //    txtT1.ReadOnly = false;
            //    txtT2.ReadOnly = false;
            //    txtT3.ReadOnly = false;
            //    txtPositionX.ReadOnly = false;
            //    txtPositionY.ReadOnly = false;
            //    btnModifyChannel.Text = "确认修改";
            //}
            //else
            //{
            //    txtAirPress.ReadOnly = true;
            //    txtTemperature.ReadOnly = true;
            //    txtPrintSpeed.ReadOnly = true;
            //    txtT1.ReadOnly = true;
            //    txtT2.ReadOnly = true;
            //    txtT3.ReadOnly = true;
            //    txtPositionX.ReadOnly = true;
            //    txtPositionY.ReadOnly = true;

            //    printProject.printChannels[cbbChannel.SelectedIndex].AirPress = double.Parse(txtAirPress.Text);
            //    printProject.printChannels[cbbChannel.SelectedIndex].Temperature = double.Parse(txtTemperature.Text);
            //    printProject.printChannels[cbbChannel.SelectedIndex].PrintSpeed = double.Parse(txtPrintSpeed.Text);
            //    printProject.printChannels[cbbChannel.SelectedIndex].T1 = double.Parse(txtT1.Text);
            //    printProject.printChannels[cbbChannel.SelectedIndex].T2 = double.Parse(txtT2.Text);
            //    printProject.printChannels[cbbChannel.SelectedIndex].T3 = double.Parse(txtT3.Text);
            //    printProject.printChannels[cbbChannel.SelectedIndex].position.X = int.Parse(txtPositionX.Text);
            //    printProject.printChannels[cbbChannel.SelectedIndex].position.Y = int.Parse(txtPositionY.Text);

            //    flashChannellabel();
            //    setChannel(cbbChannel.SelectedIndex);//修改后重新设定通道

            //    Invoke(new EventHandler(delegate
            //    {
            //        statusTips.Text = "通道参数修改完成";
            //    }));

            //    btnModifyChannel.Text = "修改";
            //}
        }
        /// <summary>
        /// 打印层 回到原点按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnToPrintZero_Click(object sender, EventArgs e)
        {
            if (Global.printProject.printLayers.Count == 0)
            {
                return;
            }
            Point3D point = Global.printProject.printLayers[Global.printer.layerIndex].points[0];
            Global.printer.moveToRelative(point.X, point.Y, point.Z, Global.printProject.printLayers[Global.printer.layerIndex].channel);
        }
        /// <summary>
        /// 打印层  导入模型按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnModifyModel_Click(object sender, EventArgs e)
        {
            if (Global.printProject.model.path == "")
            {
                MessageBox.Show("请先导入模型");
                return;
            }
            //printProject.model.moveX = float.Parse(txtModelX.Text);
            //printProject.model.moveY = float.Parse(txtModelY.Text);
            //printProject.model.moveZ = float.Parse(txtModelZ.Text);
            //printProject.model.multiple = float.Parse(txtModelMult.Text);
            //Utilities.ReadSTLFile(printProject.model.path, printProject.model);
        }
        /// <summary>
        /// 打印层 分层切片按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSlice_Click(object sender, EventArgs e)
        {
            if (Global.printProject.model.path == "")
            {
                MessageBox.Show("请先导入模型");
                return;
            }
            WindowSlice formSlice = new WindowSlice();
            //formSlice.SliceEvent += FormSlice_SliceEvent;
            //formSlice.ShowDialog();
        }
        /// <summary>
        /// 切片事件
        /// </summary>
        /// <param name="maxHeight"></param>
        /// <param name="minHeight"></param>
        /// <param name="precision"></param>
        /// <param name="fillMode"></param>
        /// <param name="fillInterval"></param>
        /// <param name="channel"></param>
        /// <param name="solidifyTime"></param>
        private void FormSlice_SliceEvent(float maxHeight, float minHeight, float precision, int fillMode, float fillInterval, int channel, int solidifyTime)
        {
            //分层
            //SliceContext sliceContext = new SliceContext(new IsothickSliceStrategy());
            //printProject.model.layers = sliceContext.executeStrategy(printProject.model, maxHeight, minHeight);
            ////填充
            //FillContext fillContext = new FillContext(new SimpleFillStrategy());
            //for (int i = 0; i < printProject.model.layers.Length; i++)
            //{
            //    List<Point3D> tempPoints = fillContext.executeStrategy(printProject.model.layers[i], fillInterval, i % 2);
            //    foreach (Point3D point in tempPoints)//换算Z轴坐标到打印平面
            //    {
            //        point.Z = planeHeight - point.Z;
            //    }
            //    PrintLayer printLayer = new PrintLayer();//打印层
            //    printLayer.points = tempPoints;
            //    printLayer.mode = 10 + fillMode;
            //    printLayer.channel = channel;
            //    printLayer.interval = fillInterval;
            //    printLayer.solidfyTime = solidifyTime;
            //    printProject.printLayers.Add(printLayer);
            //}
            Global.SliceVM.flushDgv();
        }

        /// <summary>
        /// 打印层  结束打印按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonEndPrint_Click(object sender, EventArgs e)
        {
            timerIsStop.Stop();
        }
    }
}